const fs = require('fs-extra');
const path = require('path');

/**
 * 获取文件名后缀
 * @param {string} fileName 文件名
 */
function getFileExtName(fileName) {
    if (fileName.trim()[0] === '.') {
        return '';
    }
    const index = fileName.lastIndexOf('.');
    if (index !== -1) {
        return fileName.substring(index + 1);
    }
    return '';
}

/**
 * 封装传输流的函数
 * @param {string} filePath 待读取的文件路径
 * @param {fs.writeSteam} writeSteam 待写入的流
 * @returns
 */
function pipeStream(filePath, writeSteam) {
    return new Promise((resolve, reject) => {
        const readStream = fs.createReadStream(filePath);
        readStream.on('end', async () => {
            await fs.unlink(filePath);
            readStream.close();
            resolve();
        });
        readStream.on('error', reject);
        readStream.pipe(writeSteam);
    });
}


/**
 * 根据文件信息合并文件
 * @param {string} filename 文件名
 * @param {number} length 分片数量
 * @param {string} hash 文件hash
 * @param {string} outputFolder 文件输出路径
 * @returns
 */
async function mergeFile({filename, length, hash, outputFolder}) {
    const chunks = [];
    const firstChunk = path.resolve(__dirname, outputFolder, `0-${hash}`);
    // 如果传入的分片大小
    const {size} = await fs.stat(firstChunk);
    for (let i = 0; i < length; i++) {
        const chunkName = `${i}-${hash}`;
        chunks.push(path.resolve(__dirname, outputFolder, chunkName));
    }
    const extName = getFileExtName(filename);
    const output = path.resolve(__dirname, outputFolder, `${hash}.${extName}`);
    return Promise.all(
        chunks.map((chunk, index) => {
            return pipeStream(
                chunk,
                fs.createWriteStream(output, {
                    start: index * size,
                    end: (index + 1) * size
                })
            );
        })
    );
}

module.exports = {
    pipeStream,
    mergeFile,
    getFileExtName
};
